package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.UserOrderService;
import com.sky.utils.PositionUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserOrderServiceImpl implements UserOrderService {


    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private PositionUtil positionUtil;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 创建订单
     *
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO dto) {
        //在提交订单之前需要判断配送地点是否支持配送
        //超过五公里不进行配送
        //根据地址id查询地址调用地图工具positionUtil
        StringBuilder address = new StringBuilder();
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        address.append(addressBook.getProvinceName())
                .append(addressBook.getCityName())
                .append(addressBook.getDistrictName())
                .append(addressBook.getDetail());

        positionUtil.positing(address.toString());

        Orders orders = new Orders();
        BeanUtils.copyProperties(dto,orders);

        orders.setNumber(System.currentTimeMillis()+""); //构建订单号
        orders.setStatus(Orders.PENDING_PAYMENT);        //设置订单状态
        orders.setPayStatus(Orders.UN_PAID);
        Long userId = BaseContext.getCurrentId();
        orders.setUserId(userId);                        //设置用户Id
        orders.setOrderTime(LocalDateTime.now());        //设置下单时间
        orders.setPhone(addressBook.getPhone());         //设置电话号码
        orders.setAddress(addressBook.getDetail());      //设置详细地址
        orders.setConsignee(addressBook.getConsignee()); //设置收货人

        userOrderMapper.submitOrder(orders);


        //保存订单详细信息到数据库
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.getCartBy(shoppingCart);
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orders.getId());
        for (ShoppingCart cart : list) {
            BeanUtils.copyProperties(cart,orderDetail);
            userOrderMapper.saveOrderDetail(orderDetail);
        }
        // 清空购物车数据
        shoppingCartMapper.clean(shoppingCart);

        return new OrderSubmitVO(orders.getId(),orders.getNumber(),orders.getAmount(),orders.getOrderTime());
    }



    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO dto) {
        //调用微信下单接口
        //返回预支付交易标志
        //将组合数据签名

        paySuccess(dto);

        return new OrderPaymentVO();
    }

    public void paySuccess(OrdersPaymentDTO dto){

        Orders orders = new Orders();
        orders.setNumber(dto.getOrderNumber());
        orders.setCheckoutTime(LocalDateTime.now());     //设置付款时间
        orders.setPayStatus(Orders.PAID);                //付款状态
        orders.setPayMethod(dto.getPayMethod());
        orders.setStatus(Orders.TO_BE_CONFIRMED);        //设置订单状态
        orders.setUserId(BaseContext.getCurrentId());
        ordersMapper.updateUnpaidOrder(orders);

        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + dto.getOrderNumber());

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 历史订单查询
     * @param dto
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO dto) {

        dto.setUserId(BaseContext.getCurrentId());

        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<OrderVO> orders = ordersMapper.getOrders(dto);


        List<OrderVO> result = orders.getResult().stream().peek(order -> {

            List<OrderDetail> orderDetails = orderDetailMapper.getorderDetailById(order.getId());

            order.setOrderDetailList(orderDetails);

        }).collect(Collectors.toList());

        return new PageResult(orders.getTotal(),result);
    }


    /**
     * 查询订单详情
     * @param id
     * @return
     */
    public OrderVO ordersDetail(Long id) {

        OrderVO orderVO = ordersMapper.getOrdersById(id);

        List<OrderDetail> orderDetail = orderDetailMapper.getOrderDetails(id);

        StringBuilder orderDishes = new StringBuilder();

        for (OrderDetail detail : orderDetail) {

            Dish dish = dishMapper.getDishById(detail.getDishId());

            SetmealVO setmeal = setmealMapper.getSetmealById(detail.getSetmealId());
            if(dish!=null){
                orderDishes.append(dish.getName());
            }
            if(setmeal!=null){
                orderDishes.append(setmeal.getName());
            }

        }
        orderVO.setOrderDetailList(orderDetail);
        orderVO.setOrderDishes(orderDishes.toString());
        return orderVO ;

    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {

        List<OrderDetail> orderDetails = orderDetailMapper.getorderDetailById(id);

        for (OrderDetail orderDetail : orderDetails) {

            ShoppingCart shoppingCart = new ShoppingCart();

            BeanUtils.copyProperties(orderDetail,shoppingCart);

            shoppingCart.setUserId(BaseContext.getCurrentId());

            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingCartMapper.addShoppingCartById(shoppingCart);
        }

    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        //修改订单状态，
        Orders orders = new Orders().builder()
                .id(id)
                .cancelTime(LocalDateTime.now())
                .cancelReason("用户取消")
                .status(Orders.CANCELLED).build();
        ordersMapper.updateOrder(orders);
        //退款

    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        OrderVO order = ordersMapper.getOrdersById(id);
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", id);
        map.put("content", "订单号：" + order.getNumber());

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
